package com.gin.supermarket_inventory_system.inventory.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gin.common.utils.TimeUtils;
import com.gin.supermarket_inventory_system.inventory.dao.SettlementMonthPoDao;
import com.gin.supermarket_inventory_system.inventory.entity.SettlementMonthPo;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.List;

/**
 *
 * @since : 2023/10/14 15:29
 * @author : ginstone
 * @version : v1.0.0
 **/
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class SettlementMonthServiceImpl extends ServiceImpl<SettlementMonthPoDao, SettlementMonthPo> implements SettlementMonthService {
    private final SettlementDayService settlementDayService;

    /**
     * 执行结算
     */
    @Override
    public void settle() {
        // 月份区间，起
        final String start = findStart();
        // 月份区间，止(上个月)
        final String end = TimeUtils.format(ZonedDateTime.now().minusMonths(1), TimeUtils.MONTH_FORMATTER);

        // 起始时间小于结束时间，不执行
        if (start.compareTo(end) < 0) {
            return;
        }
        final List<SettlementMonthPo> entities = settlementDayService.sumGroupByMonth(start, end).stream().map(SettlementMonthPo::new).toList();

        saveBatch(entities);

    }

    /**
     *
     * @return 返回上次月结的月份
     */
    public String findStart() {
        final QueryWrapper<SettlementMonthPo> qw = new QueryWrapper<>();
        qw.select("max(date) as date");
        final List<SettlementMonthPo> list = list(qw);
        // 没有查询结果，返回0
        if (list.get(0) == null) {
            return "1970-01";
        }
        // 有结果，返回下一个月
        final LocalDate localDate = LocalDate.parse(list.get(0).getDate(), TimeUtils.MONTH_FORMATTER);
        return localDate.plusMonths(1).format(TimeUtils.MONTH_FORMATTER);
    }

    /**
     * 每天5点执行自动结算
     */
    @Scheduled(cron = "0 0 5 * * ?")
    public void autoSettle() {
        settle();
    }
}
